package com.yncmcc.Controller;

import com.yncmcc.Controller.Interface.UserController;
import com.yncmcc.Entity.*;
import com.yncmcc.Service.Interface.AdminService;
import com.yncmcc.Service.Interface.ContractsService;
import com.yncmcc.Service.Interface.PeriodService;
import com.yncmcc.Service.Interface.UserService;
//import org.apache.shiro.SecurityUtils;
//import org.apache.shiro.authc.AuthenticationException;
//import org.apache.shiro.authc.IncorrectCredentialsException;
//import org.apache.shiro.authc.UnknownAccountException;
//import org.apache.shiro.authc.UsernamePasswordToken;
//import org.apache.shiro.subject.Subject;
//import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import com.yncmcc.Util.MD5Util;
import com.yncmcc.Util.STATUS;
import jxl.read.biff.BiffException;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import net.sf.ezmorph.object.JSONArray;
//import net.sf.json.JSONObject;

/**
 * Created by CMCC-sunmo on 2016/9/18.
 */
@Controller
@RequestMapping("/user")
public class UserControllerImpl implements UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ContractsService contractsService;
    @Autowired
    private PeriodService periodService;
    @Autowired
    private AdminService adminService;

    private Map<String , Object> response;
    public UserControllerImpl() {
        super();
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Map<String, Object> login(String userName, String userPass, HttpServletRequest request, HttpSession session) {
        response = new HashMap();
        List<AdminEntity> adminEntities = adminService.findAdminAll();
        for (int i = 0 ; i < adminEntities.size() ; i++){
            if(userName.equals(adminEntities.get(i).getAdminName())){
                if(adminService.checkPass(adminEntities.get(i).getAdminId() , userPass)){
                    response.put("status" , "ok");
                    response.put("des" , "admin");
                    session.setAttribute("adminId" , adminEntities.get(i).getAdminId());
                    session.setAttribute("adminName" , adminEntities.get(i).getAdminName());
                    session.setAttribute("adminFallName" , "管理员");
                    session.setAttribute("userRight" , 0);
                    List<DepartmentEntity> list = userService.findDepartmentOfAll();
                    session.setAttribute("DepartmentList" , JSONArray.fromObject(list));
                    return response;
                }else{
                    response.put("status" , "error");
                    response.put("des" , "管理员密码错误");
                    return response;
                }
            }
        }
        UserEntity check = userService.findByUserName(userName);
        if(check == null){
            response.put("status" , "error");
            response.put("des" , "用户名错误，请输入员工编号！");
            return response;
        }
        if(userService.checkPass(check.getUserId() , userPass)){
            response.put("status" , "ok");
            response.put("des" , "user");
            session.setAttribute("userId" , check.getUserId());
            session.setAttribute("userFullName" , check.getUserFullName());
            session.setAttribute("userName" , check.getUserName());
            session.setAttribute("deptId" , check.getDeptId());
            session.setAttribute("userRight" , check.getUserRight());
            List<DepartmentEntity> list = userService.findDepartmentOfAll();
            session.setAttribute("DepartmentList" , JSONArray.fromObject(list));
        }else{
            response.put("status" , "error");
            response.put("des" , "用户密码错误，请检查后重新输入！");
            return  response;
        }
        return  response;
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public Map<String, Object> logout(HttpServletRequest request, HttpSession session) {
        session.removeAttribute("userId");
        session.removeAttribute("userFullName");
        session.removeAttribute("userName");

        session.removeAttribute("adminId");
        session.removeAttribute("adminFullName");
        session.removeAttribute("adminName");

        session.removeAttribute("deptId");
        session.removeAttribute("userRight");
        session.removeAttribute("DepartmentList");
        response = new HashMap();
        response.put("status" , "ok");
        response.put("des","用户登出成功");
        return response;
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/addContract", method = RequestMethod.POST)
    public Map<String, Object> addContract(ContractsEntity contractsEntity, HttpServletRequest request, HttpSession session) {
        response = new HashMap();

        String des = contractsService.addContract(contractsEntity);
        if(des.equals("ok")){
            response.put("status" , "ok");
            response.put("des" , "合同添加成功");
            return response;
        }else{
            response.put("status" , "error");
            response.put("des" , des);
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/addPeriod", method = RequestMethod.POST)
    public Map<String, Object> addPeriod(PeriodEntity periodEntity, HttpServletRequest request, HttpSession session) {
        response = new HashMap();
        String  flag  = periodService.addPeriod(periodEntity);
        if(flag.equals("ok")){
            response.put("status" , "ok");
            response.put("des" , "合同分期添加成功");
            return response;
        }else{
            response.put("status" , "error");
            response.put("des" , flag);
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/getContractByID", method = RequestMethod.GET)
    public Map<String, Object> getContractByID(String contractId, HttpServletRequest request, HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        ContractsEntity contractsEntity = contractsService.findByContractID(contractId);

        if (null == contractsEntity) {
            response.put("status", "error");
            response.put("des", "合同不存在");
            return response;
        }
        else {
            response.put("status", "ok");
            response.put("des", "成功");
            response.put("data", contractsEntity);
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/getPeriodByCID", method = RequestMethod.GET)
    public Map<String, Object> getPeriodByCID(String contractId, HttpServletRequest request, HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        List<PeriodEntity> periodEntities = periodService.findByContractId(contractId);

        if (null == periodEntities || periodEntities.size() == 0 ) {
            response.put("status", "error");
            response.put("des", "本合同没有分期");
            return response;
        }
        else {
            response.put("status", "ok");
            response.put("des", "成功");
            response.put("data", periodEntities);
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/addContractByExcel", method = RequestMethod.POST)
    public Map<String, Object> addContractByExcel(MultipartFile file, HttpServletRequest request, HttpSession session) throws IOException, BiffException, ParseException{
        response = new HashMap<>();

        if(file == null){
            response.put("status","empty");
            response.put("description", "文件为空");
            return response;
        }

        String message = contractsService.addByExcel(file);
        if (StringUtils.isBlank(message)) {
            response.put("status", "ok");
            response.put("description", "批量导入成功");
        }
        else {
            response.put("status", "error");
            response.put("description", message);
        }
        return response;
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/findContract", method = RequestMethod.POST)
    public Map<String, Object> findContract(ContractsEntity contractsEntity, HttpServletRequest request, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        //deptId,userId,contractSerial,contractName,contractCate,
        //IsWarn,contractCTime,contractUTime

        List<ContractsCustomEntity> contractsEntities = contractsService.findReqContract(contractsEntity);

        if (null == contractsEntities || contractsEntities.size() == 0) {
            response.put("status", "error");
            response.put("des", "合同不存在");
            response.put("data",null);
            return response;
        }else {
            response.put("status", "ok");
            response.put("des", "成功");
            response.put("data", contractsEntities);
            return response;
        }

    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/updateContract", method = RequestMethod.POST)
    public Map<String, Object> updateContract(ContractsEntity contractsEntity, HttpServletRequest request, HttpSession session) {
        response = new HashMap<>();
        if (session.getAttribute("userId").equals("null")) {
            response.put("status", "refuse");
            response.put("des", "未登录");
            return response;
        }

        if (StringUtils.isBlank(contractsEntity.getContractId()) || StringUtils.isBlank(contractsEntity.getContractName())) {
            response.put("status", "error");
            response.put("des", "合同号或合同名为空");
            return response;
        }

        ContractsEntity oldContract = contractsService.findByContractID(contractsEntity.getContractId());//原来的合同信息

        if (null == oldContract) {
            response.put("status", "error");
            response.put("des", "合同不存在");
            return response;
        }
        oldContract.setContractSerial(contractsEntity.getContractSerial());//修改合同编号
        oldContract.setContractCate(contractsEntity.getContractCate());//修改合同类型
        oldContract.setContractName(contractsEntity.getContractName());
        String cate = oldContract.getContractCate() + "";

        if(cate.equals("1")) {
            oldContract.setSrStartTime(contractsEntity.getSrStartTime());
            oldContract.setSrEndTime(contractsEntity.getSrEndTime());
            oldContract.setSrRemindTime(contractsEntity.getSrRemindTime());
            oldContract.setSrIsWarn(contractsEntity.getSrIsWarn());
        }
        else if(cate.equals("2")){
            oldContract.setEaStartTime(contractsEntity.getEaStartTime());
            oldContract.setEaEndTime(contractsEntity.getEaEndTime());
            oldContract.setEaRemindTime(contractsEntity.getEaRemindTime());
            oldContract.setEaIsWarn(contractsEntity.getEaIsWarn());
        }
        else if(cate.equals("3")){
            oldContract.setCtStartTime(contractsEntity.getCtStartTime());
            oldContract.setCtEndTime(contractsEntity.getCtEndTime());
            oldContract.setCtRemindTime(contractsEntity.getCtRemindTime());
            oldContract.setCtPeriodNum(contractsEntity.getCtPeriodNum());
            oldContract.setCtIsWarn(contractsEntity.getCtIsWarn());
        }
        else{
            response.put("status", "error");
            response.put("des", "请先输入合同类型，再进行修改");
            return response;
        }

        int status = contractsService.updateContract(oldContract);
        if (status == STATUS.MINUS) {
            response.put("status", "minus");
            response.put("des", "金额不可为负数");
        }
        if (status == STATUS.STARTTIMEERROR) {
            response.put("status", "startTimeError");
            response.put("des", "起始时间非法");
        }
        if (status == STATUS.DEADLINEERROR) {
            response.put("status", "startTimeError");
            response.put("des", "截止时间非法");
        }
        if (status == STATUS.REMINDTIMEERROR) {
            response.put("status", "remindTimeError");
            response.put("des", "提醒时间非法");
        }
        if (status == STATUS.ID_EMPTY) {
            response.put("status", "empty");
            response.put("des", "合同不存在");
        }
        if (status == STATUS.SUCCESS) {
            response.put("status", "ok");
            response.put("des", "修改成功");
        }
        return response;
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/getSelfInfo", method = RequestMethod.GET)
    public Map<String, Object> getSelfInfo(String userId, HttpServletRequest request, HttpSession session) {
        response = new HashMap<>();
        //        String userId = (String) session.getAttribute("userId");
//        userId = request.getParameter("userId");
        UserEntity check = userService.findByUserId(userId);
        if(check == null){
            response.put("status", "error");
            response.put("des", "所查用户不存在");
            return response;
        }else{
            response.put("status", "ok");
            response.put("des", "查询成功");
            response.put("data",check);
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/updatePass", method = RequestMethod.POST)
    public Map<String, Object> updatePass(String userId, String oldPassword, String newPassword, HttpServletRequest request, HttpSession session) {
        response = new HashMap();
        UserEntity userEntity = userService.findByUserId(userId);
        if(userEntity == null){
            response.put("status" , "error");
            response.put("des" , "所查用户不存在");
            return response;
        }else if(StringUtils.isBlank(newPassword)){
            response.put("status" , "error");
            response.put("des" , "新密码不能为空！");
            return response;
        }

        if(!userService.checkPass(userId , oldPassword)){
            response.put("status" , "error");
            response.put("des" , "旧密码错误，请重新输入！");
            return response;
        }else{
            userEntity.setUserPass(MD5Util.calc(newPassword+userEntity.getUserPrimarySalt()));
            userService.updateUser(userEntity);
            response.put("status" , "ok");
            response.put("des" , "密码修改成功！");
            return response;
        }
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/updateEmail", method = RequestMethod.POST)
    public Map<String, Object> updateEmail(String email, String type, String userId, HttpServletRequest request, HttpSession session) {
        response = new HashMap();
        if(StringUtils.isBlank(userId)){
            response.put("status" , "error");
            response.put("des" , "用户Id为空！");
        }
        UserEntity userEntity = userService.findByUserId(userId);
        if(userEntity == null){
            response.put("status" , "error");
            response.put("des" , "用户不存在！");
        }
        if(type.equals("oa")){
            userEntity.setUserOaEmail(email);
        }else if(type.equals("139")){
            userEntity.setUserOrdinaryEmail(email);
        }
        String message = userService.updateUser(userEntity);
        if(!message.equals("ok")){
            response.put("status" , "error");
            response.put("des" , message);
        }else{
            response.put("status" , "ok");
            response.put("des" , "更新成功");
        }
        return response;
    }

    @Override
    @ResponseBody
    @RequestMapping(value = "/updatePeriod", method = RequestMethod.POST)
    public Map<String, Object> updatePeriod(PeriodEntity periodEntity, HttpServletRequest request, HttpSession session) {
        response = new HashMap();
        String  flag  = periodService.updatePeriod(periodEntity);
        if(flag.equals("ok")){
            response.put("status" , "ok");
            response.put("des" , "合同分期更新成功");
            return response;
        }else{
            response.put("status" , "error");
            response.put("des" , flag);
            return response;
        }
    }

    @Override
    @RequestMapping(value = "/**")
    public String errorAction() {
//        request.getRequestDispatcher(request.getContextPath()+"/login.jsp").forward(request,response);
        return "forward:/login.jsp";
    }
}